import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'
import viteCompression from 'vite-plugin-compression'
import analyzer from 'rollup-plugin-analyzer'
import electron from 'vite-plugin-electron'
import renderer from 'vite-plugin-electron-renderer'
import { notBundle } from 'vite-plugin-electron/plugin'
import pkgJson from './package.json'

function pathResolve(dir) {
  return resolve(process.cwd(), '.', dir);
}

const useDevMode = true

export default defineConfig(({ command, mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root)

  const isServe = command === 'serve'
  const isBuild = command === 'build'
  const sourcemap = isServe || !!process.env.VSCODE_DEBUG

  const { VITE_PORT, VITE_GLOB_APP_TITLE, VITE_DROP_CONSOLE, VITE_SITE_URL, VITE_APP_SHORT_NAME } = env;

  return {
    base: './',
    root,
    resolve: {
      alias: {
        '@': pathResolve('src'),
      }
    },
    define: {
      'import.meta.env.ELECTRON': true,
      "import.meta.env.VITE_GLOB_APP_TITLE": JSON.stringify(VITE_GLOB_APP_TITLE),
      "import.meta.env.VITE_APP_SHORT_NAME": JSON.stringify(VITE_APP_SHORT_NAME),
      "import.meta.env.VITE_APP_VERSION": `"${pkgJson.version}"`
    },
    plugins: [
      vue(),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_GLOB_APP_TITLE,
            ...(
                isBuild 
                ? {
                    siteUrl: VITE_SITE_URL,
                    injectScript: `<script>window.ORGCOMMON_BASE_URL="${VITE_SITE_URL}"</script>`,
                }
                : {
                  siteUrl: '',
                  injectScript: '',
                }
            )
          },
        }
      }),
      analyzer({ summaryOnly: true }),
      // 构建压缩文件
      viteCompression({
        // 是否在控制台输出压缩结果，默认为 true
        verbose: true,
        // 是否禁用压缩，默认为 false
        disable: false,
        // 启用压缩的文件大小最小限制，单位字节（byte），默认为 0，1b(字节)=8bit(比特), 1KB=1024B
        threshold: 10240, // 即10kb以上即会压缩
        // 采用的压缩算法，默认是 gzip
        algorithm: 'gzip',
        // 生成的压缩包后缀
        ext: '.gz',
      }),
      electron([
        {
          // Main process entry file of the Electron App.
          entry: 'electron/main/index.js',
          onstart({ startup }) {
            if (process.env.VSCODE_DEBUG) {
              console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')
            } else {
              startup()
            }
          },
          vite: {
            build: {
              sourcemap,
              minify: isBuild,
              outDir: 'dist-electron/main',
              // outDir: "/Users/项目管理",
              rollupOptions: {
                // Some third-party Node.js libraries may not be built correctly by Vite, especially `C/C++` addons, 
                // we can use `external` to exclude them to ensure they work correctly.
                // Others need to put them in `dependencies` to ensure they are collected into `app.asar` after the app is built.
                // Of course, this is not absolute, just this way is relatively simple. :)
                external: Object.keys('dependencies' in pkgJson ? pkgJson.dependencies : {}),
              },
            },
            plugins: [
              // This is just an option to improve build performance, it's non-deterministic!
              // e.g. `import log from 'electron-log'` -> `const log = require('electron-log')` 
              isServe && notBundle(),
            ],
          },
        },
        {
          entry: 'electron/preload/index.js',
          onstart({ reload }) {
            // Notify the Renderer process to reload the page when the Preload scripts build is complete, 
            // instead of restarting the entire Electron App.
            reload()
          },
          vite: {
            build: {
              sourcemap: sourcemap ? 'inline' : undefined, // #332
              minify: isBuild,
              outDir: 'dist-electron/preload',
              rollupOptions: {
                external: Object.keys('dependencies' in pkgJson ? pkgJson.dependencies : {}),
              },
            },
            plugins: [
              isServe && notBundle(),
            ],
          },
        }
      ]),
      // Use Node.js API in the Renderer process
      renderer(),
    ],
    esbuild: {
      jsxFactory: "jsx"
    },
    build: {
      target: "es2015",
      minify: "terser",
      cssCodeSplit: true,
      outDir: "dist",
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE,
        },
      },
      brotliSize: false,
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        input: 'index.html',
        output: {
          // 静态资源打包做处理
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          charset: false,
          modifyVars: {
            "primary-color": "#2878ff", // 全局主色
          },
          additionalData: '@import "./src/common/styles/base.less";',
        },
      },
    },
    server: {
      port: VITE_PORT,
      cors: true,
      proxy: {
        "/api": {
          target: VITE_SITE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    clearScreen: false,
  }
})
